import { useEffect, useState } from "react";
import { gatewayAPI } from "../../apis/gateway";
import { DatePicker, Table } from 'antd';
import { TableColumnType } from "../../interface";
import { Link, useRouteMatch } from "react-router-dom";
import { fmtTimeStamp } from "../../utils";

const { RangePicker } = DatePicker;

export default function ApiPerform() {
  const [metrics, setMetrics] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    start_time: 0,
    end_time: 0,
  });
  const [pager, setPager] = useState({
    pageSize: 10,
    pageIndex: 1,
    total: 0
  });

  useEffect(() => {
    getMetrics();
    getApiRank();
  }, [pager.pageIndex])

  function getMetrics() {
    gatewayAPI.getMetrics({}).then((res: any) => {
      console.log(res);
    })
  }

  function getApiRank() {
    setLoading(true);
    gatewayAPI.getPerformanceByGroup({
      ...formData,
      ...pager,
    }).then((res: any) => {
      if (res && res.success) {
        setTableData(res.data.list)
        setPager({
          ...pager,
          total: res.data.total
        })
      }
    }).finally(() => {
      setLoading(false);
    })
  }

  function onDateChange(date: any, dateString: any) {
    setFormData({
      ...formData,
      start_time: date[0].unix() * 1000,
      end_time:  date[1].unix() * 1000,
    })
  }

  const tableSize = 'middle';
  const match = useRouteMatch();

  const columns: TableColumnType[] = [
    {
      title: '接口地址',
      dataIndex: 'url',
      key: 'url',
      ellipsis: true,
      width: '30%',
      render: (t: string) => {
        return <Link to={match.path + '/' + encodeURIComponent(t)}>{t}</Link>
      }
    },
    {
      title: '最近发生时间',
      dataIndex: 'latest',
      key: 'latest',
      render: (t: number) => {
        return fmtTimeStamp(+t);
      }
    },
    {
      title: '平均响应时间',
      dataIndex: 'ava_time',
      key: 'ava_time',
    },
    {
      title: '请求总数',
      dataIndex: 'count',
      key: 'count',
    },
    {
      title: '影响用户',
      dataIndex: 'user_count',
      key: 'user_count',
    },
  ]
  return (
    <div>
      <RangePicker onChange={onDateChange} style={{ marginBottom: 16 }}/>
      <Table
        // onChange={onChange}
        rowKey={ "id" }
        bordered
        columns={ columns }
        loading={ loading }
        size={tableSize}
        dataSource={ tableData }
        pagination={{
          showQuickJumper: false,
          showTotal: () => `共 ${ pager.total } 条`,
          pageSize: pager.pageSize,
          total: pager.total,
          current: pager.pageIndex,
          onChange: (v) => setPager({
            ...pager,
            pageIndex: v,
          })
        }}
      />
    </div>
  )
}